package georeference;

/*
 * not implement yet, reserved for load xmd file
 */
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import com.esri.arcgis.beans.map.MapBean;
import com.esri.arcgis.carto.FeatureLayer;
import com.esri.arcgis.carto.Map;
import com.esri.arcgis.controls.MapControl;
import com.esri.arcgis.geodatabase.IFeature;
import com.esri.arcgis.geodatabase.IFeatureCursor;
import com.esri.arcgis.geodatabase.IField;
import com.esri.arcgis.geodatabase.IFields;
import com.esri.arcgis.geodatabase.esriFieldType;
import com.esri.arcgis.geometry.IGeoTransformation;
import com.esri.arcgis.geometry.IGeometry;
import com.esri.arcgis.geometry.IPoint;
import com.esri.arcgis.geometry.ISpatialReference;
import com.esri.arcgis.geometry.Point;
import com.esri.arcgis.geometry.Polygon;
import com.esri.arcgis.geometry.SpatialReferenceEnvironment;
import com.esri.arcgis.geometry.esriGeometryType;
import com.esri.arcgis.geometry.esriSRGeoCSType;
import com.esri.arcgis.geometry.esriSRGeoTransformationType;
import com.esri.arcgis.geometry.esriSRProjCSType;
import com.esri.arcgis.geometry.esriTransformDirection;
import com.esri.arcgis.interop.AutomationException;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;

public class MapRead {

	//Point2D p2 = new Point2D.Double(91.25888062, 28.04060936);
	//Point2D p3 = new Point2D.Double(90.7305069, 28.0649395); // long lat
	//Point2D p4 = new Point2D.Double(90.01586151, 28.29644012);
	//Point2D p5 = new Point2D.Double(89.47579193, 28.04276085);
	
	
	Point2D georeference = new Point2D.Double();
	Point2D screempoint = new Point2D.Double(83.33711243, 29.46372986);
	String filename = "";
	public MapBean map = null;
	
	public ArrayList<Polygon> borders = null;
	
	AoInitialize aoInit = null;
	
	public MapRead() throws Exception {
		borders = new ArrayList<Polygon>();
		
		// Initialize the engine and licenses.
		EngineInitializer.initializeEngine();

		aoInit = new AoInitialize();
		MapReadInitialize();
		
	}

	/*
	 * shut down the inti
	 */
	
	public void MapReadEnd() throws AutomationException, IOException{
		System.out.println("Done!");
		aoInit.shutdown();
	}
	
	
	
	/*
	 * active the lisence 
	 */
	public void MapReadInitialize()
	{
		try
		{
			
			initializeArcGISLicenses(aoInit);

			// Create a point with Geographic coordinates...
			Point point = new Point();
			point.putCoords(-100.0, 40.0);

			System.out.println("Original coordinates: " + point.getX() + "," + point.getY());

			// Create the SpatialReferenceEnvironment...
			SpatialReferenceEnvironment spatialReferenceEnvironment = new SpatialReferenceEnvironment();

			// Apply the initial spatial reference...
			ISpatialReference geographicCoordinateSystem = spatialReferenceEnvironment
					.createGeographicCoordinateSystem(esriSRGeoCSType.esriSRGeoCS_NAD1927);
			point.setSpatialReferenceByRef(geographicCoordinateSystem);

			// Create the output projected coordinate system...
			ISpatialReference projectedCoordinateSystem = spatialReferenceEnvironment
					.createProjectedCoordinateSystem(esriSRProjCSType.esriSRProjCS_NAD1983UTM_13N);

			// Create the GeoTransformation...
			IGeoTransformation iGeoTransformation = (IGeoTransformation) spatialReferenceEnvironment
					.createGeoTransformation(esriSRGeoTransformationType.esriSRGeoTransformation_NAD1927_To_WGS1984_5);

			// Project the point...
			point.projectEx(projectedCoordinateSystem, esriTransformDirection.esriTransformForward, iGeoTransformation,
					false, 0.0, 0.0);
			System.out.println("Projected coordinates: " + point.getX() + " , " + point.getY());

			

		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	
	/**
	 * Initializes the lowest available ArcGIS License
	 */
	private static void initializeArcGISLicenses(AoInitialize aoInit)
	{
		try
		{
			if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngine) == esriLicenseStatus.esriLicenseAvailable)
			{
				aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
			}
			else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeArcView) == esriLicenseStatus.esriLicenseAvailable)
			{
				aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeArcView);
			}
			else
			{
				System.err.println("Could not initialize an Engine or ArcView license. Exiting application.");
				System.exit(-1);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}	
	
	
	public MapBean getMap() throws AutomationException, IOException {
		
		if (map == null) {
			try {
				map = new MapBean();
				// Get DEVKITHOME Home
				String devKitHome = System.getenv("AGSDEVKITJAVA");
				System.out.println(devKitHome + "java" + File.separator
						+ "samples" + File.separator + "data" + File.separator
						+ "mxds" + File.separator + "brazil.mxd");

				map.loadMxFile(
						"C:\\Users\\cecile\\Desktop\\trick map\\testing.mxd",
						null, null);
			} catch (java.lang.Throwable e) {
				e.printStackTrace();
			}

		}

		System.out.println(map.getLayerCount() + "");

		return map;
	}
    
	
	
	
    public void getGeometry() throws AutomationException, IOException{

    	FeatureLayer country = new FeatureLayer(map.getLayer(0));
    	
    	IFeatureCursor featureCursor = country.search(null, true);
    	
    	
    	IFields fields = featureCursor.getFields();
    	
    	
    	int fieldCount = fields.getFieldCount();
    	for (int i = 0; i < fieldCount; i++) {
    	  IField fieldI = fields.getField(i);
    	  String fieldName = fieldI.getName();
    	  System.out.print(fieldName + "\t");
    	}
    	System.out.println();
    	
    	IFeature feature = featureCursor.nextFeature();
    	while (feature != null) {
    	  StringBuffer row = new StringBuffer();
    	  for (int i = 0; i < fieldCount; i++) {
    		  int fieldType = feature.getFields().getField(i).getType();
    		  switch (fieldType) {
    			  case esriFieldType.esriFieldTypeDate:
    			  case esriFieldType.esriFieldTypeDouble:
    			  case esriFieldType.esriFieldTypeGlobalID:
    			  case esriFieldType.esriFieldTypeGUID:
    			  case esriFieldType.esriFieldTypeInteger:
    			  case esriFieldType.esriFieldTypeOID:
    			  case esriFieldType.esriFieldTypeSingle:
    			  case esriFieldType.esriFieldTypeSmallInteger:
    			  case esriFieldType.esriFieldTypeString:
    				  row.append(feature.getValue(i) + "\t");
    				  break;
    			  case esriFieldType.esriFieldTypeBlob:
    				  row.append("(blob)" + "\t");
    				  break;
    			  case esriFieldType.esriFieldTypeGeometry:
    				  row.append("(geometry)" + "\t");
    				  break;
    			  case esriFieldType.esriFieldTypeRaster:
    				  row.append("(raster)" + "\t");
    				  break;
    		  }
    	  }
    	  
    	  if (row.length() > 0) {
    		  System.out.println(row);
    		 }
    	  
    	  
    	  if(feature.getFields().getField(0).toString().equalsIgnoreCase("0"))
    	  {
    		  // Check if the field is the shape field.
    	      IGeometry geo = feature.getShape();
      	//	  System.out.print("georeference:" + geo.getSpatialReference().getName());

    	     
    	      if(geo.getGeometryType() == esriGeometryType.esriGeometryPolygon)
    	      {
    	    	Polygon poly = (Polygon)(geo);
    	    	borders.add(poly);
    	      }
    	      
    	  }
    	  feature = featureCursor.nextFeature();  
  	  
    	}
    }
    
    
    
    
	public void setFilename(String fn){
		this.filename = fn;
	}
	
	public void readfile() throws AutomationException, IOException{
		
		if (map == null) {
		    try {
			map = new MapBean();
			map.loadMxFile("C:\\Users\\cecile\\Desktop\\trick map\\testing.mxd",
			    null, null);
		    } catch (java.lang.Throwable e) {
			e.printStackTrace();
		    }
		}
		System.out.println(map.getLayerCount() + "");

	}
	
	public MapBean readfile(String fn){
		MapBean map = null;
		
		if (map == null) {
			try {
				map = new MapBean();
				// Get DEVKITHOME Home
				String devKitHome = System.getenv("AGSDEVKITJAVA");
				System.out.println(devKitHome + "java" + File.separator
						+ "samples" + File.separator + "data" + File.separator
						+ "mxds" + File.separator + "brazil.mxd");

				map.loadMxFile( fn, null, null);
			} catch (java.lang.Throwable e) {
				e.printStackTrace();
			}

		}
		return map;
	}
	
	
	public void formatG_S(){
	 
	}
	
	public void formatS_G(){
		  
	}
}
